// 时间戳格式化
export function formatTime(date) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

// 数字格式化
export function formatNumber(n) {
    n = n.toString()
    return n[1] ? n : '0' + n
}

// Openid
export function getOpenId(cb = function(openid) {}) {
    //获取应用实例
    var app = getApp();
    if (!empty(app.globalData.openid)) {
        cb(app.globalData.openid);
    } else {
        app.openIdCallback = cb;
    }
}

// 本地存储
export class session {

    get(key) {
        return wx.getStorageSync(key)
    }

    set(key, value) {
        wx.setStorageSync(key, value);
    }

    del(key) {
        wx.setStorageSync(key, undefined);
    }

    clear() {
        wx.clearStorageSync();
    }

}

// JSON->xml
export function jsonToXml(params) {
    let builder = new xml2js.Builder();
    return builder.buildObject(params);
}

//xml -> json
export function xmlToJson(params) {
    let parser = new xml2js.Parser({
        explicitArray: false,
        ignoreAttrs: true
    });
    let json;
    parser.parseString(params, function(err, result) {
        json = result;
    });
    return json;
}

// 函数排序
export function ksort(obj) {
    if (typeof(obj) === 'object' && obj !== null) {
        let newkey = Object.keys(obj).sort();
        //先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获取的属性名进行排序，newkey是一个数组
        let newObj = {}; //创建一个新的对象，用于存放排好序的键值对
        for (let i = 0; i < newkey.length; i++) { //遍历newkey数组
            //向新创建的对象中按照排好的顺序依次增加键值对
            if (typeof(obj[newkey[i]]) === 'object' && obj !== null) {
                newObj[newkey[i]] = ksort(obj[newkey[i]]);
            } else {
                newObj[newkey[i]] = obj[newkey[i]];
            }
        }
        return newObj; //返回排好序的新对象
    } else {
        return obj;
    }
}

// 校验$value是否非空
export function empty($value) {
    if (typeof($value) === "undefined") {
        return true;
    } else if ($value === null) {
        return true;
    } else if (typeof($value) === 'string' && trim($value) === '') {
        return true;
    } else if (typeof($value) === 'object' && (JSON.stringify($value) === '{}' || JSON.stringify($value) === '[]')) {
        return true;
    } else {
        return false;
    }
}

// 删除空格
export function trim(str) {
    return String(str).replace(/(^\s*)|(\s*$)/g, "");
}

// url字符串中提取域名
export function domainName(url) {
    var sign = "://";
    var pos = url.indexOf(sign);
    //如果以协议名开头
    //如：http://github.com/
    if (pos >= 0) {
        pos += sign.length;
        //截取协议名以后的部分
        //github.com/
        url = url.slice(pos);
    }
    //以/作分割
    var array = url.split("/");
    return array[0];
}

/**
 * 系统返回数据状态
 * [0] 业务逻辑失败
 * [1] 业务逻辑成功
 * [2] 处理业务时发生错误，系统会重发3次
 * [3] AccessToken验证失败
 */
export function responseResult(ResponseResult) {
    let msg;
    if (typeof ResponseResult === 'object') {
        switch (Number(ResponseResult.code)) {
            case -1:
                msg = ResponseResult.msg;
                break;
            case 0:
                msg = '业务逻辑失败';
                break;
            default:
                msg = '错误代码:' + ResponseResult.code;
        }
    } else {
        msg = '服务器发生异常';
    }
    wx.showModal({
        content: msg,
        showCancel: false,
    });
    const error = new Error(ResponseResult);
    error.response = ResponseResult;
    throw error;
}

// 消息提示
export function message(msg, success, fail) {
    let OBJECT = {};
    if (typeof msg == 'object') {
        if (!empty(msg.title)) {
            OBJECT = Object.assign(OBJECT, {
                title: msg.title,
            });
        }
        if (!empty(msg.content)) {
            OBJECT = Object.assign(OBJECT, {
                content: msg.content,
            });
        }
    } else if (typeof msg == 'string') {
        OBJECT = Object.assign(OBJECT, {
            content: msg,
        });
    }

    if (empty(success) && empty(fail)) {
        OBJECT = Object.assign(OBJECT, {
            showCancel: false,
        });
    }

    if (!empty(success) && !empty(fail)) {
        OBJECT = Object.assign(OBJECT, {
            success: function(res) {
                if (res.confirm) {
                    success()
                } else if (res.cancel) {
                    fail()
                }
            }
        });
    }

    if (!empty(success)) {
        OBJECT = Object.assign(OBJECT, {
            showCancel: false,
            success: function(res) {
                if (res.confirm) {
                    if (res.confirm) {
                        success()
                    }
                }
            }
        });
    }
    wx.showModal(OBJECT);
}

export function toast(msg, icon = 'none', duration = 2000, success = function() {}, fail = function() {}, complete = function() {}) {
    let obj = {
        title: msg,
        icon: icon,
        duration: duration,
        success: () => {
            success()
        },
        fail: () => {
            fail()
        },
        complete: () => {
            complete()
        }
    }
    wx.showToast(obj)
}